<!-- Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -->
<!DOCTYPE html>
<title>Unit Test of e2e.openpgp.KeyClient</title>
<script src="../../../closure/base.js"></script>
<script src="test_js_deps-runfiles.js"></script>
<script>
  goog.require('goog.array');
  goog.require('goog.net.XhrIo');
  goog.require('goog.testing.AsyncTestCase');
  goog.require('goog.testing.jsunit');
  goog.require('goog.testing.net.XhrIo');
  goog.require('goog.testing.PropertyReplacer');
  goog.require('e2e.async.Result');
  goog.require('e2e.cipher.all');
  goog.require('e2e.cipher.Aes');
  goog.require('e2e.cipher.Algorithm');
  goog.require('e2e.openpgp.block.TransferablePublicKey');
  goog.require('e2e.openpgp.block.factory');
  goog.require('e2e.openpgp.KeyClient');
  goog.require('e2e.hash.Sha1');
  goog.require('e2e.signer.Algorithm');
  goog.require('e2e.signer.Ecdsa');
</script>
<!--
:public key packet:
  version 4, algo 19, created 1408716939, expires 0
  unknown algorithm 19
:user ID packet: "<ecc@example.com>"
:signature packet: algo 19, keyid A91985B3AA980DC1
  version 4, created 1408716939, md5len 0, sigclass 0x10
  digest algo 8, begin of digest f9 06
  critical hashed subpkt 2 len 4 (sig created 2014-08-22)
  critical hashed subpkt 16 len 8 (issuer key ID A91985B3AA980DC1)
  unknown algorithm 19
:public sub key packet:
  version 4, algo 18, created 1408716939, expires 0
  unknown algorithm 18
:signature packet: algo 19, keyid A91985B3AA980DC1
  version 4, created 1408716939, md5len 0, sigclass 0x18
  digest algo 8, begin of digest 7d 8f
  critical hashed subpkt 2 len 4 (sig created 2014-08-22)
  critical hashed subpkt 16 len 8 (issuer key ID A91985B3AA980DC1)
  unknown algorithm 19
-->
<textarea id="pubKeyAscii">
-----BEGIN PGP PUBLIC KEY BLOCK-----
Charset: UTF-8

xv8AAABSBFP3UIsTCCqGSM49AwEHAgMEjt37zqFShFGWQs2XsjXe82RAjD0ULivh
wPVyqt/Bvn2eTTzWB9Bv5SDIaHI5m979ThVRRKlSMGQIiK2Il71wus3/AAAAETxl
Y2NAZXhhbXBsZS5jb20+wv8AAABmBBATCAAY/wAAAAWCU/dQi/8AAAAJkKkZhbOq
mA3BAAD5BgD/VVQ2Zjsv/pJeTRUeAjSB6k7tr1UyQneZ6/V1NHJZ0x8A/0lITTKZ
TZKyZLb+TejK9k9F7s0m9zZn4q4JxFWDbkOizv8AAABWBFP3UIsSCCqGSM49AwEH
AgMERvFPl1fK8weTLuZRhFkbC28BVFyW7WL5BoOZ0noaHsLb+GPpXSU4O9H593Bw
uYpu0ZNL7ueWkyFJPuNFGyG4lwMBCAfC/wAAAGYEGBMIABj/AAAABYJT91CL/wAA
AAmQqRmFs6qYDcEAAH2PAQD4vU9agaX1njxMXgF8nsqGAu1UWF+2M0t/JVQ9+YFC
hwEA1RFEzURGNJbObccP6oJGdBdL0A6YpZNLI2hXyISsU2A=
=taNi
-----END PGP PUBLIC KEY BLOCK-----
</textarea>
<script>

var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(document.title);
var keyText = '-----BEGIN%20PGP%20PUBLIC%20KEY%20BLOCK-----%0D%0ACharset%3A%20UTF-8%0D%0A%0D%0A' +
    'xv8AAAAMBAAAAAABAAYjAAURzf8AAAAMZmlyc3QgdXNlcmlk%0D%0A%3DKc%2Fi%0D%0A-----END%20PGP%20PUBL' +
    'IC%20KEY%20BLOCK-----';
/** @type {goog.testing.PropertyReplacer} */
var stubs = new goog.testing.PropertyReplacer();
var keyClient = new e2e.openpgp.KeyClient('http://127.0.0.1:8888');
var key = e2e.openpgp.block.factory.parseBlock([
  new e2e.openpgp.packet.PublicKey(
    4, 0, e2e.cipher.factory.get(
      e2e.cipher.Algorithm.RSA,
      {n: [35], e: [17]}),
    goog.array.repeat(17, 20)),
  new e2e.openpgp.packet.UserId('first userid')
]);

function setUp() {
  stubs.replace(goog.net.XhrIo, 'send', goog.testing.net.XhrIo.send);
  stubs.replace(keyClient, 'getOpenIdCredentials_', function() {
    return e2e.async.Result.toResult({
      credentials: {postBody: 'x', requestUri: 'y'},
      port: {close: function() {}}});
  });
  stubs.replace(e2e.random, 'getRandomBytes', function() {
    return [0];
  });
}

function tearDown() {
  stubs.reset();
  goog.array.clear(goog.testing.net.XhrIo.getSendInstances());
}

function testAddPublicKeyOKStatusCode() {
  var result = keyClient.importPublicKey(key);
  var xhrios = goog.testing.net.XhrIo.getSendInstances();
  assertEquals(1, xhrios.length);
  assertEquals('POST', xhrios[0].getLastMethod());
  assertEquals('http://127.0.0.1:8888/pks/add', xhrios[0].getLastUri());
  assertEquals(
    'keytext=' + keyText +'&nonce=00&requestUri=y&postBody=x', xhrios[0].getLastContent());
  asyncTestCase.waitForAsync('Waiting for response to be processed.');
  xhrios[0].simulateResponse(200, '');
  result.addCallback(function(isSucceeded) {
    assertEquals(true, isSucceeded);
    asyncTestCase.continueTesting();
  });
}

function testAddPublicKeyNotOKStatusCode() {
  var result = keyClient.importPublicKey(key);
  var xhrios = goog.testing.net.XhrIo.getSendInstances();
  assertEquals(1, xhrios.length);
  assertEquals('POST', xhrios[0].getLastMethod());
  assertEquals('http://127.0.0.1:8888/pks/add', xhrios[0].getLastUri());
  assertEquals(
    'keytext=' + keyText +'&nonce=00&requestUri=y&postBody=x', xhrios[0].getLastContent());
  asyncTestCase.waitForAsync('Waiting for response to be processed.');
  xhrios[0].simulateResponse(500, '');
  result.addCallback(function(isSucceeded) {
    assertEquals(false, isSucceeded);
    asyncTestCase.continueTesting();
  });
}

function testSearchPublicKeyFoundValidKey() {
  var email = 'test@google.com';
  var pubKeys = keyClient.searchPublicKey(email);
  var xhrios = goog.testing.net.XhrIo.getSendInstances();
  assertEquals(1, xhrios.length);
  assertEquals('GET', xhrios[0].getLastMethod());
  assertEquals(
      'http://127.0.0.1:8888/pks/lookup?op=get&x-email=test%40google.com',
      xhrios[0].getLastUri());
  asyncTestCase.waitForAsync('Waiting for response to be processed.');
  xhrios[0].simulateResponse(200, document.getElementById('pubKeyAscii').value);
  pubKeys.addCallback(function(pubKeys) {
    assertEquals(1, pubKeys.length);
    assertEquals('<ecc@example.com>', pubKeys[0].getUserIds()[0]);
    asyncTestCase.continueTesting();
  });
}

function testSeachPublicKeyFoundInvalidKey() {
  var email = 'test@google.com';
  var pubKeys = keyClient.searchPublicKey(email);
  var xhrios = goog.testing.net.XhrIo.getSendInstances();
  assertEquals(1, xhrios.length);
  assertEquals('GET', xhrios[0].getLastMethod());
  assertEquals(
      'http://127.0.0.1:8888/pks/lookup?op=get&x-email=test%40google.com',
      xhrios[0].getLastUri());
  asyncTestCase.waitForAsync('Waiting for response to be processed.');
  xhrios[0].simulateResponse(200, 'invalid key');
  pubKeys.addCallback(function(pubKeys) {
    assertArrayEquals([], pubKeys);
    asyncTestCase.continueTesting();
  });
}


function testSearchPublicKeyNotFound() {
  var email = 'test@google.com';
  var pubKeys = keyClient.searchPublicKey(email);
  var xhrios = goog.testing.net.XhrIo.getSendInstances();
  assertEquals(1, xhrios.length);
  assertEquals('GET', xhrios[0].getLastMethod());
  assertEquals(
      'http://127.0.0.1:8888/pks/lookup?op=get&x-email=test%40google.com',
      xhrios[0].getLastUri());
  asyncTestCase.waitForAsync('Waiting for response to be processed.');
  xhrios[0].simulateResponse(400, '');
  pubKeys.addCallback(function(pubKeys) {
    assertArrayEquals([], pubKeys);
    asyncTestCase.continueTesting();
  });
}

</script>
